<?php

namespace app\admin\controller;

use app\common\Helper;
use app\admin\model\Userbuyticket;
use app\admin\model\User;
use app\admin\model\Store;
use app\admin\model\Ticket;

use think\Db;
use think\Exception;
use think\Request;

/**
 * 订单
 */
class Order extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $this->model = new Userbuyticket();
    }

    /**
     * 列表
     */
    public function getList(){
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            'a.status' => 1
        ];
        if($this->admin->roleType != 1){
            $where['s.province'] = $this->admin->province;
            if($this->admin->city != '所有') {
                $where['s.city'] = $this->admin->city;
            }
        }
        if (isset($param->storeName)) {
            $where['a.storeName'] = ['like', '%' . $param->storeName . '%'];
        }

        $model = $this->model;
        $order = 'a.createDate DESC';
        $join = [
            ['store s', 's.id = a.storeId']
        ];
        $field = 'a.*, s.name, s.imgurl';
        $result = $model->alias('a')->where($where)->join($join)->limit($start, $length)->order($order)->field($field)->select();
        $total = $model->alias('a')->where($where)->join($join)->count();

        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关订单');
        }

        foreach ($result as $item) {
            $userInfo = User::where(['id' => $item['userId']])->find();
            $item['userName'] = $userInfo['userName'];
            $item['userAvatar'] = $userInfo['imgUrl'];
            $item['storeImg'] = Store::where(['id' => $item['storeId']])->value('imgUrl');
            $item['ticketName'] = Ticket::where(['id' => $item['ticketId']])->value('specialOfferStatement');
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

}